var sizeConfig = {
    photoSite: 'https://image.nicepatches.com/',
    pcSite: 'https://www.nicepatches.com/',
    mobileSite: 'https://m.nicepatches.com/',
    //pcSite: 'http://w.nicepatches.com/',
    //mobileSite: 'http://mobile.nicepatches.com/',
};

(function ($) {
    $.zero = {};

    //获取url参数
    $.zero.getQueryString = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return "";
    };

    //获取url参数,带默认值
    $.zero.getQueryString = function (name, defaultValue) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return defaultValue;
    };

    $.zero.setCurrentQueryString = function setCurrentQueryString(key, value) {
        var href = window.location.href;
        href = $.zero.setQueryString(href, key, value);
        history.pushState({}, '', href);
    };

    $.zero.clearCurrentQueryString = function clearCurrentQueryString() {
        var href = window.location.href;
        href = href.split('?')[0];
        history.pushState({}, '', href);
    };

    $.zero.removeCurrentQueryString = function removeCurrentQueryString(keys) {
        var href = window.location.href;
        var keyList = keys.split(',');
        for (var i = 0; i < keyList.length; i++) {
            href = $.zero.removeQueryString(href, keyList[i]);
        }
        history.pushState({}, '', href);
    };

    //参数值不为空时，存在参数则更新，否则不操作
    $.zero.removeQueryString = function removeQueryString(uri, key) {
        if (uri === null) {
            return uri;
        }
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        if (uri.match(re)) {
            uri = uri.replace(re, function (rs, $1, $2) {
                if ($2 === '&') {
                    return $1;
                }
                return '';
            });
            return uri;
        }
        return uri;
    };

    //获取url的参数部分
    $.zero.getQueryList = function getQueryList(params) {
        var obj = {};

        //[^&=]+ 表示不含&或=的连续字符，加上()就是提取对应字符串
        params.replace(/([^&=]+)=([^&=]*)/gi, function (rs, $1, $2) {
            obj[$1] = $2;
        });
        return obj;
    };

    //参数值不为空时，存在参数则更新，否则不操作
    $.zero.setQueryString = function setQueryString(uri, key, value) {
        if (uri === null) {
            return uri;
        }
        if (!value) {
            return uri;
        }
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        var separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re)) {
            return uri.replace(re, '$1' + key + "=" + value + '$2');
        }
        else {
            return uri + separator + key + "=" + value;
        }
    };

    $.zero.getPhoto = function getPhoto(photoData, index, width, height) {
        if (photoData === null || photoData === '[]') {
            return '';
        }
        photoData = JSON.parse(photoData);

        if (photoData.length <= index)
            return '';

        if (photoData[index].url === '')
            return '';

        var url = photoData[index].url;
        url = url.replace(".", '_' + width + 'x' + height + '_0.');
        return sizeConfig.photoSite + 'tb' + url;
    };

    $.zero.contain = function contain(searchValue, value) {
        return searchValue.indexOf(value) !== -1 ? true : false;
    };

    /*
    函数：根据条件从对象数组中获取一个对象
    参数：匿名函数，字段，值
    返回：查找到的对象，如果没有查找到返回null
    调用方式：var result=find(list,function (o) { return o.Age>30; });
    var result=find(list,function () { return this.Age>30; });
    var result=find(list,"Age",22);
    var result=find(list,{Age:22});
    */
    $.zero.find = function find(source, property, value) {
        if (source == undefined || source == null) {
            return null;
        }

        var tp = typeof property, fn;
        switch (tp) {
            case "function":
                fn = property;
                break;
            case "object":
                fn = function () { return $.zero.equal(this, property); };
                break;
            default:
                fn = function () { return this[property] == value; };
                break;
        }
        for (var i = 0, len = source.length; i < len; i++) {
            var o = source[i];
            if (fn.call(o, o)) {
                return o;
            }
        }
        return null;
    };

    /*
    函数：根据条件查询对象数组
    参数：匿名函数；字段，值
    返回：查找到的对象数组
    调用方式：var result=where(list,function (m) { return m.Age>30; });
    var result=where(list,function () { return this.Age>30; });
    var result=where(list,"Age",22);
    var result=where(list,{Age:22});
    */
    $.zero.where = function where(source, property, value) {
        if (source == undefined || source == null) {
            return [];
        }

        var arr = [], tp = typeof property, fn;
        switch (tp) {
            case "function":
                fn = property;
                break;
            case "object":
                fn = function () { return $.zero.equal(this, property); };
                break;
            default:
                fn = function () { return this[property] == value; };
                break;
        }
        for (var i = 0, len = source.length; i < len; i++) {
            var o = source[i];
            if (fn.call(o, o)) {
                arr.push(o);
            }
        }
        return arr;
    };

    /*
    函数：根据条件查询对象数组
    参数：匿名函数；字段，值
    返回：查找到的对象数组
    调用方式：var result=where(list,function (m) { return m.Age>30; });
    var result=where(list,function () { return this.Age>30; });
    var result=where(list,"Age",22);
    var result=where(list,{Age:22});
    */
    $.zero.remove = function remove(source, property, value) {
        if (source == undefined || source == null) {
            return [];
        }

        var arr = [], tp = typeof property, fn;
        switch (tp) {
            case "function":
                fn = property;
                break;
            case "object":
                fn = function () { return $.zero.equal(this, property); };
                break;
            default:
                fn = function () { return this[property] == value; };
                break;
        }
        for (var i = 0, len = source.length; i < len; i++) {
            var o = source[i];
            if (fn.call(o, o)) {
                source.splice(i, 1);
            }
        }
        return arr;
    };

    /*
    函数：简单对象相等比较,比较两个对象中的所有属性（不包含继承或通过prototype扩展的）是否全部相等
    参数：目标要比较的对象
    返回：相等返回true,否则返回false
    调用方式：var result=equal(sourceObj,{Id:66,Age:66});
    */
    $.zero.equal = function equal(sourceObj, targetObj) {
        for (var key in targetObj) {
            if (sourceObj[key] != targetObj[key]) {
                return false;
            }
        }
        return true;
    };

    //增加日期
    $.zero.addDate = function addDate(date, days) {
        var d = new Date(date);
        d.setDate(d.getDate() + days);
        var m = d.getMonth() + 1;
        return d.getFullYear() + '-' + m + '-' + d.getDate();
    };

    //比较2个日期
    $.zero.compareDate = function CompareDate(d1, d2) {
        return ((new Date(d1.replace(/-/g, "\/"))) > (new Date(d2.replace(/-/g, "\/"))));
    };

    //计算不同年份不同月相差多少月份
    $.zero.getIntervalMonth = function getIntervalMonth(startDate, endDate) {
        var startMonth = startDate.getMonth();
        var endMonth = endDate.getMonth();
        var intervalMonth = (endDate.getFullYear() * 12 + endMonth) - (startDate.getFullYear() * 12 + startMonth) ;
        return intervalMonth;
    };

    //添加
    /*
     * c_key 键名
     * c_val 值
     * c_time 单位为秒的失效时间
     */
    $.zero.addCookie = function addCookie(c_key, c_val, c_time) {
        document.cookie = c_key + "=" + c_val + ";max-age=" + c_time;
    };

    //获取
    $.zero.getCookieWithKey = function getCookieWithKey(c_key, d_value) {
        if ($.zero.hasCookieWithKey(c_key)) {
            for (var i = 0; i < arr.length; i++) {
                var temp = arr[i].split("=");
                if (temp[0].trim() === c_key) {
                    return temp[1];
                }
            }
        }
        else {
            return d_value;
        }
    };

    //修改
    $.zero.setCookieWithKey = function setCookieWithKey(c_key, v_val, c_time) {
        if (hasCookieWithKey(c_key)) {
            addCookie(c_key, v_val, c_time);
        }
    };

    //删除
    $.zero.deleteCookieWithKey = function deleteCookieWithKey(c_key) {
        setCookieWithKey(c_key, "", -1);
    };

    //是否含有某个键名
    $.zero.hasCookieWithKey = function hasCookieWithKey(c_key) {
        var arr = document.cookie.split("; ");
        for (var i = 0; i < arr.length; i++) {
            var temp = arr[i].split("=");
            if (temp[0].trim() === c_key) {
                return true;
            }
        }
        return false;
    };

    $.zero.isEmpty = function isEmpty(value) {
        if (value === null || value === '') {
            return true;
        }
        return false;
    };

    $.zero.showValidationErrorMsg = function showValidationErrorMsg(msg) {
        var content = msg.error.message;
        if (msg.error.validationErrors != null) {
            for (var i = 0; i < msg.error.validationErrors.length; i++) {
                content += "<br>" + msg.error.validationErrors[i].message;
            }
        }
        $.zero.showErrorMsg(content);
    };

    $.zero.showErrorMsg = function showErrorMsg(content) {
        layer.open({
            type: 1,
            skin: "mod_pop",
            title: false,
            closeBtn: 1,
            time: 10000,
            area: ['auto', 'auto'], //宽高
            shadeClose: true,
            //content: "<div class='success_msg error_msg'><i class='iconfont'>&#xe713;</i><h5>Sorry!</h5><p class='desc'>#content</p></div>".replace('#content', content)
            content: "<div class='success_msg error_msg'><p>#content</p></div>".replace('#content', content)
        });
    };

    $.zero.showWarnMsg = function showErrorMsg(content) {
        layer.open({
            type: 1,
            skin: "mod_pop",
            title: false,
            closeBtn: 1,
            time: 10000,
            area: ['auto', 'auto'], //宽高
            shadeClose: true,
            content: "<div class='success_msg error_msg'><p>#content</p></div>".replace('#content', content)
        });
    };


})(jQuery);

Number.prototype.toDecimal = function () {
    var f = Math.round(this * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return parseFloat(s);
};

Number.prototype.toDecimalString = function () {
    var s = this.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    // console.log(s);
    // console.log(parseFloat(s));
    return s;
}

// 清除两边的空格  
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, '');
};

// String转化为Number  
String.prototype.ToInt = function () {
    return isNaN(parseInt(this)) ? this.toString() : parseInt(this);
};

// 获取文件全名  
String.prototype.GetFileName = function () {
    var regEx = /^.*\/([^\/\?]*).*$/;
    return this.replace(regEx, '$1');
};

// 获取文件扩展名  
String.prototype.GetExtensionName = function () {
    var regEx = /^.*\/[^\/]*(\.[^\.\?]*).*$/;
    return this.replace(regEx, '$1');
};

//替换所有
String.prototype.replaceAll = function (reallyDo, replaceWith, ignoreCase) {
    if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);
    } else {
        return this.replace(reallyDo, replaceWith);
    }
}; 